package com.xfunc.ok.dmok;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
public class DManager {

    public static DManager getInstance() {
        return INSTANCE.instance;
    }
    public static class INSTANCE{
        static DManager instance = new DManager();
    }
    private OkHttpClient mClient = new OkHttpClient.Builder()
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .build();
    //用来存放各个下载的请求
    private HashMap<String, Call> downCalls = new HashMap<>();
    //用来存放各个下载的请求的回调
    private HashMap<String, ProgressListener> listeners = new HashMap<>();
    void println(String message) {
        System.out.println(" " + message);
    }
    void cancel(String url) {
        println("请求取消下载");
        if (downCalls.containsKey(url)) {
            println("执行取消下载：$url");
            downCalls.get(url).cancel();
            downCalls.remove(url);
        }
        if (listeners.containsKey(url)) {
            listeners.get(url).cancel(url);
            listeners.remove(url);
        }
    }
    /**
     * 开始下载
     * @param urlTemp      下载请求的网址
     * @param listenerTemp 用来回调的接口
     */
    void download(String urlTemp, ProgressListener listenerTemp) {
        if (listenerTemp != null) {
            listeners.put(urlTemp, listenerTemp);
        }
        //第一步 过滤 call的map中已经有了,就证明正在下载,则这次不下载
        if (downCalls.containsKey(urlTemp)) {
            ProgressListener tempP = listeners.get(urlTemp);
            if(tempP!=null){
                tempP.onRepeat(urlTemp);
            }
            return;
        }
        //第二步 查询本地缓存中是否存在已经下载的文件
        ProgressListener tempPP = listeners.get(urlTemp);
        if(tempPP!=null){
            tempPP.onReady(urlTemp);
        }
        BufferedRandomAccessFile randomAccessFile = null;
        BufferedInputStream bis = null;
        Response response = null;
        BufferedSource source = null;
        try {
            DownloadInfo downloadInfo = new DownloadInfo(urlTemp);
            long contentLength = 0L;
            if (queryCache(urlTemp)) {

            } else {
                //第二步 获取下载长度
                contentLength = getContentLength(urlTemp); //获得文件大小
                //第三步 创建下载信息
                downloadInfo.total = contentLength;
                String fileName = urlTemp.substring(urlTemp.lastIndexOf("/"));
                downloadInfo.fileName = fileName;
                downloadInfo = getRealFileName(downloadInfo, FILE_PATH_JAVA);
            }
            //此处判断是否完成下载，大小比较
            //第四步 创建请求 并设置回调
            long downloadLength = downloadInfo.progress; //已经下载好的长度
            contentLength = downloadInfo.total; //文件的总长度
            String bytesRange = String.format("bytes=%s-%s", downloadLength, contentLength);
            Request request = new Request.Builder() //确定下载的范围,添加此头,则服务器就可以跳过已经下载好的部分
                    .addHeader("RANGE", bytesRange)
                    .addHeader("x-oss-range-behavior", "standard")
                    .url(downloadInfo.url)
                    .build();
            if (contentLength == -1L) {
                request = request.newBuilder().removeHeader("RANGE").build();
            }
            Call call = mClient.newCall(request);
            // 第五步 执行请求 把这个添加到call里,方便取消
            downCalls.put(downloadInfo.url, call);
            response = call.execute();
            System.out.println("response：${response.code}  $bytesRange");
            // 第六步 设置进度回调
            ResponseBody responseBody = ProgressHelper.withProgress(response.body(), listeners.get(urlTemp));
            source = responseBody.source();
            //第七步 将数据写入到本地文件中去
            File outFile = new File(FILE_PATH_JAVA, downloadInfo.fileName);
            if (response.isSuccessful()) {
                if (response.code() == 206) {
                    ProgressListener tempP = listeners.get(urlTemp);
                    if(tempP!=null){
                        tempP.onSupportBreakpointContinuation(urlTemp, true);
                    }
                    // 随机访问文件，可以指定断点续传的起始位置
                    randomAccessFile = new BufferedRandomAccessFile(outFile, "rw");
                    randomAccessFile.seek(downloadInfo.progress);
                    byte[] buff = new byte[1024 * 4];
                    int len = 0;
                    bis = new BufferedInputStream(source.inputStream());
                    while ((len = bis.read(buff)) != -1) {
                        randomAccessFile.write(buff, 0, len);
                    }
                    randomAccessFile.flush();
                } else {
                    // 不支持断点续传删除，先删除然后重新创建
                    boolean delete = outFile.delete();
                    boolean newFile = outFile.createNewFile();
                    ProgressListener tempP = listeners.get(urlTemp);
                    if(tempP!=null){
                        tempP.onSupportBreakpointContinuation(urlTemp, false);
                    }
                    BufferedSink sink = Okio.buffer(Okio.sink(outFile));
                    source.readAll(sink);
                    sink.flush();
                    sink.close();
                }
            } else {
                ProgressListener tempP = listeners.get(urlTemp);
                if(tempP!=null){
                    tempP.onError(urlTemp, "下载失败");
                }
            }
        } catch (Exception e) {
            ProgressListener tempP = listeners.get(urlTemp);
            if(tempP!=null){
                tempP.onError(urlTemp, "出错了。。。");
            }
            e.printStackTrace();
            println("下载异常。。。");
        } finally {
            if(response!=null){
                response.close();
            }
            try {
                if(randomAccessFile!=null){
                    randomAccessFile.close();
                }
            }catch (Exception e){}
            try {
                if(source!=null){
                    source.close();
                }
            }catch (Exception e){}
            //第八步 移除当前call
            downCalls.remove(urlTemp);
            listeners.remove(urlTemp);
        }
    }

    private Boolean queryCache(String url) {
        return false;
    }

    /**
     * 获取下载长度
     *
     * @param downloadUrl
     * @return
     */
    private long getContentLength(String downloadUrl) {
        Request request = new Request.Builder().url(downloadUrl).build();
        try (Response response = mClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                Map<String, List<String>> toMultimap = response.headers().toMultimap();
                if (response.body() == null) return 0;
                return response.body().contentLength();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        println("getContentLength");
        return 0;
    }

    String FILE_PATH_JAVA = System.getProperty("user.dir") + File.separator + "func_temp";

    /**
     * 如果文件已下载重新命名新文件名
     *
     * @param downloadInfo
     * @return
     */
    private DownloadInfo getRealFileName(DownloadInfo downloadInfo, String absolutePath) throws IOException {
        String fileName = downloadInfo.fileName;
        long downloadLength = 0L;
        long contentLength = downloadInfo.total;
        File path = new File(absolutePath == null || absolutePath.isEmpty() ? FILE_PATH_JAVA : absolutePath);
        if (!path.exists()) {
            path.mkdir();
        }
        File file = new File(path, fileName);
        if (file.exists()) {
            //找到了文件,代表已经下载过,则获取其长度
            downloadLength = file.length();
        }
        //之前下载过,需要重新来一个文件
        int i = 1;
        File newFile = null;
        while (downloadLength >= contentLength) {
            int dotIndex = fileName.lastIndexOf(".");
            String fileNameOther = (dotIndex == -1) ? (fileName + i) : fileName.substring(0, dotIndex) + "(" + i + ")" + fileName.substring(dotIndex);
            newFile = new File((absolutePath == null || absolutePath.isEmpty() ? FILE_PATH_JAVA : absolutePath), fileNameOther);
            file = newFile;
            downloadLength = newFile.length();
            i++;
        }
        if (!newFile.exists()) {
            newFile.createNewFile();
        }
        //设置改变过的文件名/大小
        downloadInfo.progress = downloadLength;
        downloadInfo.fileName = file.getName();
        println("getRealFileName");
        return downloadInfo;
    }
}
